﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace PmSoft.Web.Abstractions.Filters;

/// <summary>
/// 全局模型验证过滤器
/// </summary>
public class GlobalModelValidationFilter : IActionFilter
{
	public void OnActionExecuting(ActionExecutingContext context)
	{
		if (!context.ModelState.IsValid)
		{
			var errors = context.ModelState
					.Where(m => m.Value?.Errors.Count > 0)
					.Select(m => new
					{
						Field = m.Key,
						Error = m.Value?.Errors.Select(e => e.ErrorMessage).FirstOrDefault()
					});

			// 如果模型验证失败，直接返回结果，不执行动作
			context.Result = new BadRequestObjectResult(new ApiResult
			{
				Msg = "输入验证失败",
				Success = false,
				Code = "VALIDATION_ERROR",
				Data = errors
			});
		}
	}

	public void OnActionExecuted(ActionExecutedContext context)
	{
		// 无需操作
	}
}
